﻿using System.Collections.Generic;
using Microsoft.Practices.SharePoint.Common.Configuration;
using SharePoint.Contrib.Extensions;

namespace SharePoint.Contrib.ApplicationSettings
{
    internal abstract class SettingCollection : ISettingCollection
    {
        protected IPropertyBag Properties;
        protected IConfigManager ConfigManager;

        public SettingCollection(IPropertyBag properties)
        {
            this.Properties = properties;
            this.ConfigManager = SPG.ConfigManager;
        }

        public virtual Setting<T> FindById<T>(string id)
        {
            Setting<T> setting = new Setting<T>
            {
                Id = id,
                Value = default(T)
            };
            
            if (ConfigManager.ContainsKeyInPropertyBag(id, Properties) == false)
            {
                "Did not find a setting with key: {0}"
                    .ThrowAsException(id);
            }
            setting.Value = ConfigManager.GetFromPropertyBag<T>(id, Properties);

            return setting;
        }


        public virtual void Add(Setting instance)
        {
            Update(instance);
        }

        public virtual void Update(Setting instance)
        {
            ConfigManager.SetInPropertyBag(instance.Id, instance.Value, Properties);
        }

        public virtual void Delete(Setting instance)
        {
            if (ConfigManager.ContainsKeyInPropertyBag(instance.Id, Properties))
            {
                ConfigManager.RemoveKeyFromPropertyBag(instance.Id, Properties);
            }
        }

        protected abstract IEnumerable<Setting> FindAll();

        public virtual IEnumerator<Setting> GetEnumerator()
        {
            return FindAll().GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return FindAll().GetEnumerator();
        }

        public void Delete(string id)
        {
            Delete(new Setting(id));
        }
    }
}
